/**
 * url: https://101.zoo.team/shu-xue/shu-xue-part-1-luo-ma-shu-zi-zhuan-zheng-shu-fizz-buzz-he-ji-shu-zhi-shu
 * 
 * LeetCode: https://leetcode-cn.com/problems/roman-to-integer/
 * 
 * 输入:"III"
 * 输出:3
 *
 * 输入 :"IV"
 * 输出:4
 * 
 * 输入:"LVIII"
 * 输出:58
 * 
 * 输入:"MCMXCIV"
 * 输出:1994
 * 
 */

/**
 * 遍历 num
 * 先看两位再看一位
 */

const romanToIntOne1 = (num) => {
    let list = {
        'I': 1,
        'V': 5,
        'X': 10,
        'L': 50,
        'C': 100,
        'D': 500,
        'M': 1000
    }
    
    // 长度是1
    if (num.length == 1) return list[num]
    
    let roman = {
        'IV': 4,
        'IX': 9,
        'XL': 40,
        'XC': 90,
        'CD': 400,
        'CM': 900
    }
    
    let res = 0;
    
    for (let i = 0 ; i < num.length ;) {
        if (roman[num.substring(i, i+2)]) {
            res += roman[num.substring(i, i+2)]
            i += 2;
        } else {
            res += list[num.substring(i, i+1)]
            i++
        }
    }
    return res
}


/**
 * 遍历 预备值
 */
const romanToIntOne2 = (num) => {
    let list = {
        'I': 1,
        'V': 5,
        'X': 10,
        'L': 50,
        'C': 100,
        'D': 500,
        'M': 1000
    }
    
    // 长度是1
    if (num.length == 1) return list[num]
    
    let roman = {
        'IV': 4,
        'IX': 9,
        'XL': 40,
        'XC': 90,
        'CD': 400,
        'CM': 900
    }
    
    let res = 0
    
    // 先遍历特殊值
    for (let s in roman) {
        if (num.includes(s)) {
            res += roman[s]
            num = num.replace(new RegExp(s) ,'')
        }
    }
    
    // 遍历 num 剩下的数值
    for (let s of num) {
        res += list[s]
    }
    
    return res
}

/**
 * switch + includes
 * 先遍历所有的罗马数值，将其相加，对于特殊的数字将其减去
 */
const romanToIntOne3 = (num) => {
    let res = 0;
    
    for (let s of num) {
        switch (s) {
            case 'I': res += 1 ; break;
            case 'V': res += 5 ; break;
            case 'X': res += 10 ; break;
            case 'L': res += 50 ; break;
            case 'C': res += 100 ; break;
            case 'D': res += 500 ; break;
            case 'M': res += 1000 ; break;
        }
    }
    
    // 减去特殊值
    if (num.includes('IV') || num.includes('IX')) res -= 2; 
    if (num.includes('XL') || num.includes('XC')) res -= 20;
    if (num.includes('CD') || num.includes('CM')) res -= 200;
    
    return res
    
}

